// @ts-ignore
import { vue } from '@/main'

export const utils = {
  toTimeFormat,
  toTypeFormat,
  tips,
  getTimeNum
}

function toTimeFormat (t: number, f: string = 'yyyy-MM-dd') {
  if (t) {
    const newDate = new Date(t)
    const date: IDate = {
      'M+': newDate.getMonth() + 1,
      'd+': newDate.getDate(),
      'h+': newDate.getHours(),
      'm+': newDate.getMinutes(),
      's+': newDate.getSeconds(),
      'q+': Math.floor((newDate.getMonth() + 3) / 3),
      'S+': newDate.getMilliseconds()
    }
    if (/(y+)/i.test(f)) {
      f = f.replace(RegExp.$1,
        (newDate.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (const k in date) {
      if (new RegExp('(' + k + ')').test(f)) {
        f = f.replace(RegExp.$1,
          RegExp.$1.length === 1 ? date[k].toString() : ('00' + date[k]).substr(
            ('' + date[k]).length).toString())
      }
    }
    return f
  } else {
    return ''
  }
}

function getTimeNum (key: string, timestamp: Number) {
  let date = key.substring(0,19)
  date = date.replace(/-/g,'/')
  timestamp = new Date(date).getTime()
  return timestamp
}

function toTypeFormat (key: string | number, types: ProductTypes[]): string {
  let currentItem = types.filter((type) => {
    return key === type.value
  })[0] || {}
  return currentItem.label
}

function tips (res: AjaxResponse): boolean {
  vue.$notify({
    title: '提示',
    message: res.responseDesc,
    type: res.responseCode === 200 ? 'success' : 'error'
  })
  return res.responseCode === 200
}

interface IDate {
  [name: string]: number
}
